package com.hdu.clj.fitness

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.util.Size
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.app.NotificationCompat
import androidx.core.text.isDigitsOnly
import androidx.core.view.GravityCompat
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_main.*
import java.io.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ActivityCollector.addActivity(this)

        //Icon显示
        val startIcon = Typeface.createFromAsset(assets,"iconfont.ttf")
        planIcon.setTypeface(startIcon)
        planIcon.setText(R.string.plan)
        resetIcon.setTypeface(startIcon)
        resetIcon.setText(R.string.reset)
        clearIcon.setTypeface(startIcon)
        clearIcon.setText(R.string.clear)
        updateTextIcon.setTypeface(startIcon)
        updateTextIcon.setText(R.string.OK)
        deleteUpTextIcon.setTypeface(startIcon)
        deleteUpTextIcon.setText(R.string.NO)
        dayTaskIcon.setTypeface(startIcon)
        dayTaskIcon.setText(R.string.card)
        menuUser.setTypeface(startIcon)
        menuUser.setText(R.string.user)
        menuAchievementIcon.setTypeface(startIcon)
        menuAchievementIcon.setText(R.string.achievement)
        modNameIcon.setTypeface(startIcon)
        modNameIcon.setText(R.string.modName)
        modPassIcon.setTypeface(startIcon)
        modPassIcon.setText(R.string.modPass)
        exitIcon.setTypeface(startIcon)
        exitIcon.setText(R.string.exit)
        showMenu.setTypeface(startIcon)
        showMenu.setText(R.string.menu)
        talkIcon.setTypeface(startIcon)
        talkIcon.setText(R.string.talk)



        //通知
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            val channel = NotificationChannel("normal","Normal",NotificationManager.IMPORTANCE_DEFAULT)
            manager.createNotificationChannel(channel)
        }

        //获取数据库版本号
        var ver = 1
        if (load("ver").isNotEmpty()){
            ver = load("ver").toInt()
        }
        //获取当前登录的用户名
        var curUserName = load("userName")
        //获取当前登录的账号
        val curUserAcc = load("userAcc")

        //获取当前用户的运动数据
        //用户总数据表
        val dbHelper = userDatabase(this,"Users.db",1)
        val db = dbHelper.writableDatabase
        //用户日常数据表
        val dbDayNum = DayNumDatabase(this,"Fit.db",ver,"abc"+curUserAcc.toString())
        val dbDay = dbDayNum.writableDatabase

        var cur_data = 0
        var inc_data = 0
        var dayNum = 1000
        var totalNum = 10000
        var newdata = 0
        var cur_dayNum = 0
        var cardNum = 0
        var curTotal = 0
        var cur_card = 0

        var curUserData = db.rawQuery("select * from Users where acc = ?", arrayOf(curUserAcc.toString()))
        if (curUserData.moveToFirst()){
            dayNum = curUserData.getInt(curUserData.getColumnIndex("dayNum"))
            totalNum = curUserData.getInt(curUserData.getColumnIndex("totalNum"))
            cur_data = curUserData.getInt(curUserData.getColumnIndex("total"))
        }

        var curTitle = ""
        var curColor = ""
        var curSize = ""
        var listtext = showWel(cur_data)
        curTitle = listtext[0]
        curColor = listtext[1]
        curSize = listtext[2]
        welTitle.setText(curTitle)
        welTitle.setTextSize(curSize.toFloat())
        welTitle.setTextColor(Color.parseColor(curColor))
        welUser.setText("的  $curUserName")
        //获取当前日期
        //获取表名
        val dataName = "abc"+curUserAcc
        val date = SimpleDateFormat("yyyy/MM/dd").format(Date()).toString()
        var curUserDayData = dbDay.rawQuery("select * from $dataName where date = ?", arrayOf(date))
        if (curUserDayData.moveToFirst()){
            //获取今天的运动情况
            cur_dayNum = curUserDayData.getInt(curUserDayData.getColumnIndex("num"))
        }
        else{
            //今天未记录，创建今天的运动情况
            dbDay.execSQL("insert into $dataName (date,num) values(?,0)", arrayOf(date))
        }

        //显示进度条
        progressTotal.progress = cur_data*100/totalNum
        progressDay.progress = cur_dayNum*100/dayNum
        totalPlanText.setText("阶段目标完成度 ：$cur_data/$totalNum")
        dayPlanText.setText("每日目标完成度 ：$cur_dayNum/$dayNum")
        //每日打卡
        if (cur_dayNum>=dayNum){
            dayTaskIcon.setTextColor(Color.parseColor("#4CAF50"))
            dayTaskIcon.isClickable = true
            dayTaskIcon.isEnabled = true
        }
        else{
            dayTaskIcon.setTextColor(Color.parseColor("#8D8989"))
            dayTaskIcon.isClickable = false
            dayTaskIcon.isEnabled = false
        }
        //打开菜单
        showMenu.setOnClickListener {
            drawerLayout.openDrawer(GravityCompat.START)
        }
        //记录总个数
        showText.setText(cur_data.toString())
        //添加数据
        updateTextIcon.setOnClickListener {

            var curUserData = db.rawQuery("select * from Users where acc = ?", arrayOf(curUserAcc.toString()))
            if (curUserData.moveToFirst()){
                dayNum = curUserData.getInt(curUserData.getColumnIndex("dayNum"))
                totalNum = curUserData.getInt(curUserData.getColumnIndex("totalNum"))
                curTotal = curUserData.getInt(curUserData.getColumnIndex("curTotal"))
            }

            curUserDayData = dbDay.rawQuery("select * from $dataName where date = ?", arrayOf(date))
            if (curUserDayData.moveToFirst()){
                //获取今天的运动情况
                cur_dayNum = curUserDayData.getInt(curUserDayData.getColumnIndex("num"))
                cur_card = curUserDayData.getInt(curUserDayData.getColumnIndex("card"))
            }
            else{
                //今天未记录，创建今天的运动情况
                dbDay.execSQL("insert into $dataName (date,num,card) values(?,0,0)", arrayOf(date))
            }


            if (editText.text.isNotEmpty()){
                if(editText.text.isDigitsOnly()) {
                    if (editText.text.toString().length < 9) {
                        inc_data = editText.text.toString().toInt()
                        cur_data = cur_data + inc_data
                        cur_dayNum = cur_dayNum + inc_data
                        curTotal = curTotal + inc_data
                        //更新数据库
                        db.execSQL(
                            "update Users set total = ? where acc = ?",
                            arrayOf(cur_data, curUserAcc)
                        )
                        db.execSQL(
                            "update Users set curTotal = ? where acc = ?",
                            arrayOf(curTotal, curUserAcc)
                        )
                        dbDay.execSQL(
                            "update $dataName set num = ? where date = ?",
                            arrayOf(cur_dayNum, date)
                        )

                        showText.setText(cur_data.toString())
                        editText.text.clear()
                        //刷新进度条
                        progressTotal.progress = curTotal * 100 / totalNum
                        totalPlanText.setText("阶段目标 ：$curTotal/$totalNum")
                        progressDay.progress = cur_dayNum * 100 / dayNum
                        dayPlanText.setText("每日目标 ：$cur_dayNum/$dayNum")
                        //发送打卡通知
                        if (cur_dayNum>=dayNum&&cur_card==0){
                            val intent_day = Intent(this,DaytaskActivity::class.java)
                            val pi_day = PendingIntent.getActivity(this,0,intent_day,0)
                            val notification = NotificationCompat.Builder(this,"normal")
                                .setContentTitle("每日打卡")
                                .setContentText("太棒了，今日任务已完成，请点击前往打卡！")
                                .setLargeIcon(BitmapFactory.decodeResource(resources,R.drawable.ts_1))
                                .setSmallIcon(R.drawable.card)
                                .setContentIntent(pi_day)
                                .setAutoCancel(true)
                                .build()
                            manager.notify(1,notification)
                        }
                        //刷新称号
                        listtext = showWel(cur_data)
                        curTitle = listtext[0]
                        curColor = listtext[1]
                        curSize = listtext[2]
                        welTitle.setText(curTitle)
                        welTitle.setTextSize(curSize.toFloat())
                        welTitle.setTextColor(Color.parseColor(curColor))
                        curUserName = load("userName")
                        welUser.setText("的  $curUserName")
                        //每日打卡
                        if (cur_dayNum >= dayNum) {
                            dayTaskIcon.setTextColor(Color.parseColor("#4CAF50"))
                            dayTaskIcon.isClickable = true
                            dayTaskIcon.isEnabled = true
                        } else {
                            dayTaskIcon.setTextColor(Color.parseColor("#8D8989"))
                            dayTaskIcon.isClickable = false
                            dayTaskIcon.isEnabled = false
                        }
                        Toast.makeText(this, "添加成功！", Toast.LENGTH_SHORT).show()
                    }
                    else{
                        Toast.makeText(this, "咱能不能诚实点！", Toast.LENGTH_SHORT).show()
                    }
                }
                else{
                    Toast.makeText(this,"请确保输入的是纯数字！",Toast.LENGTH_SHORT).show()
                }
            }
            else{
                Toast.makeText(this,"请输入数据！",Toast.LENGTH_SHORT).show()
            }

        }

        resetIcon.setOnClickListener {


            AlertDialog.Builder(this).apply {
                setTitle("注意")
                setMessage("本操作会清除历史数据但不会重置累计的总数，是否继续！")
                setPositiveButton("继续"){_,_->

//                    db.execSQL("update Users set total = ? where name = ?", arrayOf(0,curUserName))
                    db.execSQL("update Users set dayNum = ? where acc = ?", arrayOf(1000,curUserAcc))
                    db.execSQL("update Users set totalNum = ? where acc = ?", arrayOf(10000,curUserAcc))
                    db.execSQL("update Users set curTotal = ? where acc = ?", arrayOf(0,curUserAcc))

                    dbDay.execSQL("delete from $dataName")
                    var curUserData = db.rawQuery("select * from Users where acc = ?", arrayOf(curUserAcc.toString()))
                    if (curUserData.moveToFirst()){
                        cardNum = curUserData.getInt(curUserData.getColumnIndex("cardNum"))
                    }
                    if (cardNum>0){
                        db.execSQL("update Users set cardNum = cardNum-1 where acc = ?", arrayOf(curUserAcc))
                    }
//                    dayTask.setText("今日未完成")
                    dayTaskIcon.setTextColor(Color.parseColor("#8D8989"))
                    dayTaskIcon.isClickable = false
                    dayTaskIcon.isEnabled = false
                    dayNum = 1000
                    totalNum = 10000
//                    cur_data = 0
                    cur_dayNum = 0

//                    showText.setText("0")
                    totalPlanText.setText("阶段目标 ：0/$totalNum")
                    progressTotal.progress = 0
                    dayPlanText.setText("每日目标 ：0/$dayNum")
                    progressDay.progress = 0
                }
                setNegativeButton("取消"){_,_->

                }
                show()
            }
        }
        clearIcon.setOnClickListener {
            AlertDialog.Builder(this).apply {
                setTitle("注意")
                setMessage("本操作会清除历史数据以及重置已经累计的总数，是否继续！")
                setPositiveButton("继续"){_,_->

                    db.execSQL("update Users set total = ? where acc = ?", arrayOf(0,curUserAcc))
                    db.execSQL("update Users set dayNum = ? where acc = ?", arrayOf(1000,curUserAcc))
                    db.execSQL("update Users set totalNum = ? where acc = ?", arrayOf(10000,curUserAcc))
                    db.execSQL("update Users set cardNum = ? where acc = ?", arrayOf(0,curUserAcc))
                    db.execSQL("update Users set curTotal = ? where acc = ?", arrayOf(0,curUserAcc))
                    dbDay.execSQL("delete from $dataName")
//                    dayTask.setText("今日未完成")
                    dayTaskIcon.setTextColor(Color.parseColor("#8D8989"))
                    dayTaskIcon.isClickable = false
                    dayTaskIcon.isEnabled = false
                    dayNum = 1000
                    totalNum = 10000
                    cur_data = 0
                    cur_dayNum = 0

                    showText.setText("0")
                    welTitle.setText("初入江湖 ")
                    welTitle.setTextSize(18f)
                    welTitle.setTextColor(Color.parseColor("#67A5AD"))
                    totalPlanText.setText("阶段目标 ：0/$totalNum")
                    progressTotal.progress = 0
                    dayPlanText.setText("每日目标 ：0/$dayNum")
                    progressDay.progress = 0
                }
                setNegativeButton("取消"){_,_->

                }
                show()
            }

        }
        planIcon.setOnClickListener {
            val intent = Intent(this,PlanActivity::class.java)
            startActivity(intent)
        }

        dayTaskIcon.setOnClickListener {
            val intent = Intent(this,DaytaskActivity::class.java)
            startActivity(intent)
        }
        deleteUpTextIcon.setOnClickListener {
            editText.text.clear()
        }

        modName.setOnClickListener {
            val intent = Intent(this,ModNameActivity::class.java)
            startActivity(intent)
        }
        modPass.setOnClickListener {
            val intent = Intent(this,modPassActivity::class.java)
            startActivity(intent)
        }
        exit.setOnClickListener {
            ActivityCollector.finshAll()
//            android.os.Process.killProcess(android.os.Process.myPid())
        }
        talk.setOnClickListener {
            val intent = Intent(this,talkActivity::class.java)
            startActivity(intent)
        }
        menuAchievement.setOnClickListener {
            val intent = Intent(this,AchievementActivity::class.java)
            startActivity(intent)
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityCollector.removeActivity(this)
    }

    override fun onResume() {
        super.onResume()

        //获取数据库版本号
        var ver = 1
        if (load("ver").isNotEmpty()){
            ver = load("ver").toInt()
        }
        //获取当前登录的用户名
        val curUserAcc = load("userAcc")
        val curUserName = load("userName")

        welUser.setText("的  $curUserName")

        //获取当前用户的运动数据
        //用户总数据表
        val dbHelper = userDatabase(this,"Users.db",1)
        val db = dbHelper.writableDatabase
        //用户日常数据表
        val dbDayNum = DayNumDatabase(this,"Fit.db",ver,"abc"+curUserAcc.toString())
        val dbDay = dbDayNum.writableDatabase

        var cur_data = 0
        var inc_data = 0
        var dayNum = 1000
        var totalNum = 10000
        var newdata = 0
        var cur_dayNum = 0
        var cardNum = 0
        var curTotal = 0

        val dataName = "abc"+curUserAcc
        val date = SimpleDateFormat("yyyy/MM/dd").format(Date()).toString()

        var curUserData = db.rawQuery("select * from Users where acc = ?", arrayOf(curUserAcc.toString()))
        if (curUserData.moveToFirst()){
            dayNum = curUserData.getInt(curUserData.getColumnIndex("dayNum"))
            totalNum = curUserData.getInt(curUserData.getColumnIndex("totalNum"))
            curTotal = curUserData.getInt(curUserData.getColumnIndex("curTotal"))
        }
        var curUserDayData = dbDay.rawQuery("select * from $dataName where date = ?", arrayOf(date))
        if (curUserDayData.moveToFirst()){
            //获取今天的运动情况
            cur_dayNum = curUserDayData.getInt(curUserDayData.getColumnIndex("num"))
        }
        progressTotal.progress = curTotal*100/totalNum
        totalPlanText.setText("阶段目标 ：$curTotal/$totalNum")
        progressDay.progress = cur_dayNum*100/dayNum
        dayPlanText.setText("每日目标 ：$cur_dayNum/$dayNum")
        //每日打卡
        if (cur_dayNum>=dayNum){
            dayTaskIcon.setTextColor(Color.parseColor("#4CAF50"))
            dayTaskIcon.isClickable = true
            dayTaskIcon.isEnabled = true
        }
        else{
            dayTaskIcon.setTextColor(Color.parseColor("#8D8989"))
            dayTaskIcon.isClickable = false
            dayTaskIcon.isEnabled = false
        }

    }

    private fun showWel(num:Int):List<String>{
        var text = ""
        var textcolor = ""
        var textsize = ""
        if (num<1000){
            text = "初入江湖 "
            textcolor = "#67A5AD"
            textsize = "18f"
        }
        else if (num<5000){
            text = "小试牛刀 "
            textcolor = "#096C79"
            textsize = "18f"
        }
        else if (num<10000){
            text = "小有所成 "
            textcolor = "#3F99E0"
            textsize = "20f"
        }
        else if (num<15000){
            text = "声名鹊起 "
            textcolor = "#3FD844"
            textsize = "20f"
        }
        else if (num<25000){
            text = "风生水起 "
            textcolor = "#8BC34A"
            textsize = "22f"
        }
        else if (num<45000){
            text = "独占鳌头 "
            textcolor = "#D0DF41"
            textsize = "22f"
        }
        else if (num<80000){
            text = "平步青云 "
            textcolor = "#E2D029"
            textsize = "24f"
        }
        else if (num<100000){
            text = "名满天下 "
            textcolor = "#F3CE5C"
            textsize = "24f"
        }
        else if (num<150000){
            text = "举世无双 "
            textcolor = "#FF5722"
            textsize = "25f"
        }
        else if (num<200000){
            text = "一代宗师 "
            textcolor = "#E22011"
            textsize = "25f"
        }
        else if (num<1000000){
            text = "飞升成仙 "
            textcolor = "#EE1C63"
            textsize = "26f"
        }
        else{
            text = "臭不要脸"
            textcolor = "#3F51B5"
            textsize = "26f"
        }

        return listOf(text,textcolor,textsize)
    }

    private fun load(data:String): String {
        val content = StringBuilder()

        try {
            val input = openFileInput(data)
            //val reader = BufferedReader(InputStreamReader(input))
            val reader = BufferedReader(InputStreamReader(input))
            reader.use {
                reader.forEachLine {
                    content.append(it)
                }
            }
        }catch (e:IOException){
            e.printStackTrace()
        }
        return content.toString()
    }
}
